/**
 * 
 */
package anyware.common.restlet.gsp;

import groovy.text.SimpleTemplateEngine;
import groovy.text.TemplateEngine;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.Map;

import org.apache.commons.lang.Validate;
import org.restlet.data.MediaType;
import org.restlet.resource.OutputRepresentation;

/**
 * @author keke<keke@codehaus.org>
 * @version 0.0.1
 */
public class TemplateRepresentation extends OutputRepresentation {
    private final Map<String, Object> binding;
    private TemplateEngine            engine;
    private final InputStream         template;

    public TemplateRepresentation(final InputStream tempateInput,
            final Map<String, Object> binding, final MediaType mediaType) {
        super(mediaType);
        Validate.notNull(tempateInput);
        template = tempateInput;
        this.binding = binding;
    }

    @Override
    public void write(final OutputStream outputStream) throws IOException {
        TemplateEngine templateEngine = engine;
        if (templateEngine == null) {
            templateEngine = new SimpleTemplateEngine();
        }
        try {
            templateEngine.createTemplate(new InputStreamReader(template))
                    .make(binding)
                    .writeTo(new OutputStreamWriter(outputStream));
        } catch (final Exception e) {
            throw new RuntimeException(e);
        }
    }

}
